package com.dbq.fast.business.me;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.h5.H5ContainerActivity;
import com.dbq.fast.business.login.NewLoginActivity;
import com.dbq.fast.business.login.bean.CustomProfile;
import com.dbq.fast.business.main.MainActivity;
import com.dbq.fast.business.me.api.RewardApi;
import com.dbq.fast.business.me.bean.ActiveMoney;
import com.dbq.fast.business.me.fragment.BindWxFragment;
import com.dbq.fast.business.order.OrderListActivity;
import com.dbq.fast.business.setting.SettingActivity;
import com.dbq.fast.common.base.BaseActivity;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.manager.DatabaseManager;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.common.net.glide.GlideApp;
import com.dbq.fast.util.ProgressDialogUtil;
import com.dbq.fast.util.RudenessScreenHelper;
import com.dbq.fast.util.SystemUtil;
import com.yiba.vpn.utils.Constants;
import com.yiba.vpn.utils.RxBus;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.processors.FlowableProcessor;

import static com.dbq.fast.analysis.EventConstant.EVENT_EXIT_ME;
import static com.dbq.fast.business.h5.H5ContainerActivity.WHICH_IS_HELP;

public class MeActivity extends BaseActivity {
    private final static int START_VPN_LOGIN_REQUEST_CODE = 100;
    public static int sIsWithdrawing = 0;

    ImageView userIcon;
    TextView vpnIdTV;
    TextView activeMoneyTV;
    CustomProfile profile;

    FlowableProcessor<String> startVpnListener;
    private RelativeLayout feedback;

    ActiveMoney mActiveMoney;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me);

        sIsWithdrawing = 0;
        initView();
        initListener();
        doRequest();

    }

    @Override
    protected void onResume() {
        super.onResume();
        profile = DatabaseManager.getInstance().queryProfile();
        if (profile == null) {
            vpnIdTV.setVisibility(View.GONE);
            feedback.setVisibility(View.GONE);
            userIcon.setImageResource(R.drawable.ic_default_head);
        } else {
            vpnIdTV.setVisibility(View.VISIBLE);
            feedback.setVisibility(View.VISIBLE);
            loadUserInfo();
        }
    }

    private void doRequest() {
        RewardApi.queryActiveMoney(new RemoteApiCallBack<ActiveMoney>() {
            @Override
            public void onFail(int status, String message) {

            }

            @Override
            public void onSuccess(ActiveMoney activeMoney) {
                showWithDrawView(activeMoney);
            }
        });

    }

    @SuppressLint("StringFormatInvalid")
    private void showWithDrawView(ActiveMoney activeMoney) {
        mActiveMoney = activeMoney;

        activeMoneyTV.setVisibility(View.VISIBLE);
        activeMoneyTV.setText(getString(R.string.active_money_num, "¥" + activeMoney.getBalance()/100f));

        Drawable dL = getResources().getDrawable(R.drawable.ic_active_money);
        Drawable dR = getResources().getDrawable(R.drawable.ic_little_right_arrow);

        int threshold = mActiveMoney.getRestrict();
        if (mActiveMoney.getStatus() == 1 ||
                mActiveMoney.getBalance() < threshold) {
            activeMoneyTV.setTextColor(getResources().getColor(R.color.active_money_unavailable));
            dR = getResources().getDrawable(R.drawable.ic_little_right_arrow_grey);
        } else {
            activeMoneyTV.setTextColor(getResources().getColor(R.color.active_money));
        }

        dL.setBounds(0, 0, (int) RudenessScreenHelper.dp2px(App.getContext(), 26.7f), (int) RudenessScreenHelper.dp2px(App.getContext(), 27.3f));
        dR.setBounds(0, 0, (int) RudenessScreenHelper.dp2px(App.getContext(), 8f), (int) RudenessScreenHelper.dp2px(App.getContext(), 12.7f));
        activeMoneyTV.setCompoundDrawables(dL, null, dR, null);
    }

    @SuppressLint("StringFormatInvalid")
    private void loadUserInfo() {
        try {
            GlideApp.with(this)
                    .load(R.drawable.ic_visitor_head)
                    .into(userIcon);
        } catch (Exception e) {
        }

        vpnIdTV.setText(getString(R.string.vpn_id, "" + User.getInstance().getVpnId()));
    }


    private void initListener() {
        startVpnListener = RxBus.get().register(Constants.RXBUS_START_VPN, String.class);
        startVpnListener.onBackpressureBuffer().observeOn(AndroidSchedulers.mainThread()).subscribe(s -> {
            switch (s) {
                case Constants.RXBUS_VPN_NODE_LOADED:
                    if (isResume) {
                        profile = DatabaseManager.getInstance().queryProfile();
                        if (profile == null) return;
                        loadUserInfo();
                    }
                    break;
            }
        });

        findViewById(R.id.back).setOnClickListener(view -> {
            onBackPressed();
        });
        findViewById(R.id.setting).setOnClickListener(view -> {
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_SETTING);
            startActivity(new Intent(this, SettingActivity.class));
        });
        findViewById(R.id.my_order_area).setOnClickListener(view -> {
            if (profile == null) {
                startActivityForResult(new Intent(this, NewLoginActivity.class), START_VPN_LOGIN_REQUEST_CODE);
            } else {
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_ME_ORDER);
                startActivity(new Intent(MeActivity.this, OrderListActivity.class));
            }
        });
        findViewById(R.id.use_help_area).setOnClickListener(view -> {
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_ME_HELP);
            Intent intent = new Intent(this, H5ContainerActivity.class);
            intent.putExtra("which", WHICH_IS_HELP);
            startActivity(intent);
        });
        feedback.setOnClickListener(v -> {
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_FEEDBACK);
            Intent intent = new Intent(this, FeedbackActivity.class);
            startActivity(intent);
        });
        findViewById(R.id.copy).setOnClickListener(view -> {
            copyVpnId(User.getInstance().getVpnId());
        });
        findViewById(R.id.withdraw_area).setOnClickListener(view -> {
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_WITHDRAW_ITEM);
            startActivity(new Intent(MeActivity.this, WithdrawActivity.class));
        });
        findViewById(R.id.reward_area).setOnClickListener(view -> {
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_MY_REWARD_ITEM);
            startActivity(new Intent(MeActivity.this, RewardActivity.class));
        });
        activeMoneyTV.setOnClickListener(view -> {
            withdraw();
        });
        findViewById(R.id.accountmanager).setOnClickListener(v -> {
            enterAccountManagerPage();
        });
    }

    private void enterAccountManagerPage() {
        Intent intent = new Intent(MeActivity.this, AccountManagerActivity.class);
        startActivity(intent);
    }

    /**
     * 提现
     */
    @SuppressLint("StringFormatInvalid")
    private void withdraw() {
        if (mActiveMoney == null) return;

        Bundle bundle = new Bundle();
        if (mActiveMoney.getIsBindWx() == 0 && BindWxFragment.sIsBindWx == 0) {
            bundle.putString("request_condition", EventConstant.PARAM_WITHDRAW_NEED_BIND_WX);
            BindWxFragment.showBindWxDialog(getSupportFragmentManager());
        } else {
            int threshold = mActiveMoney.getRestrict();
            if (mActiveMoney.getStatus() == 1 || sIsWithdrawing == 1) {
                Toast.makeText(App.getContext(), getString(R.string.tip_reject_has_withdraw), Toast.LENGTH_SHORT).show();
                bundle.putString("request_condition", EventConstant.PARAM_WITHDRAW_WITHDRAWING);
            } else if (mActiveMoney.getBalance() < threshold) {
                Toast.makeText(App.getContext(), getString(R.string.tip_reject_money_not_enough, "¥" + threshold/100f), Toast.LENGTH_SHORT).show();
                bundle.putString("request_condition", EventConstant.PARAM_WITHDRAW_MONEY_NOT_ENOUGH);
            } else {
                bundle.putString("request_condition", EventConstant.PARAM_WITHDRAW_MEET_CRITERIA);
                ProgressDialogUtil.showProgress(this, "", getString(R.string.commiting));
                RewardApi.withdraw(mActiveMoney.getBalance(), new RemoteApiCallBack() {
                    @Override
                    public void onFail(int status, String message) {
                        if(isResume){
                            ProgressDialogUtil.hideProgress();
                        }
                        Toast.makeText(App.getContext(), getString(R.string.tip_retry_network_bad), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(Object o) {
                        sIsWithdrawing = 1;
                        if(isResume){
                            ProgressDialogUtil.hideProgress();
                        }
                        Toast.makeText(App.getContext(), App.getContext().getString(R.string.tip_receive_withdraw_request), Toast.LENGTH_SHORT).show();
                    }
                });

            }
        }
        YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_REQUEST_WITHDRAW, bundle);
    }

    private void copyVpnId(String text) {
        Toast.makeText(App.getContext(), App.getContext().getString(R.string.tip_copy_success), Toast.LENGTH_SHORT).show();
        SystemUtil.copyToBoad(text);
    }

    private void initView() {
        userIcon = findViewById(R.id.userIcon);
        feedback = findViewById(R.id.upload);
        vpnIdTV = findViewById(R.id.vpn_id);
        activeMoneyTV = findViewById(R.id.active_money);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == START_VPN_LOGIN_REQUEST_CODE) {
            if (resultCode == MainActivity.RESULT_OK) {
                if (User.getInstance().isNewUser()) { //新用户
                    setResult(RESULT_OK);
                    finish();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        YibaAnalysis.getInstance().event(App.getContext(), EVENT_EXIT_ME);
        RxBus.get().unregister(Constants.RXBUS_START_VPN, startVpnListener);
        if(isResume){
            ProgressDialogUtil.hideProgress();
        }
        super.onDestroy();
    }
}
